
package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.SoulReportApi;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.OptionsVo;
import com.tanhua.server.vo.QuestionsVo;
import com.tanhua.server.vo.SoulReportVo;
import com.tanhua.server.vo.SoulVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SoulService {

    @Reference(version = "1.0.0")
    private SoulReportApi soulReportApi;

    @Autowired
    private UserInfoService userInfoService;

    public SoulReportVo querySoulReport(String reportId) {
        User user = UserThreadLocal.get();
        SoulReport soulReport = this.soulReportApi.queryReportById(reportId);
        SoulReportVo soulReportVo = new SoulReportVo();
        soulReportVo.setConclusion(soulReport.getConclusion());
        soulReportVo.setCover(soulReport.getCover());
        Map<String, String> dimensions = soulReport.getDimensions();
        //获取mongodb 里面所有的维度
        /*List<Dimension> dimensions = soulReport.getDimensions();

        for (Dimension dimension : dimensions) {
            Dimensions ds = new Dimensions();
            ds.setKey(dimension.getKey());
            ds.setValue(dimension.getValue());
            dimensionsvo.add(ds);
        }*/
        //需要返回给前端的维度数据
        List<Dimensions> dimensionsvo = new ArrayList<>();
        dimensionsvo.add(new Dimensions("外向", dimensions.get("外向")));
        dimensionsvo.add(new Dimensions("判断", dimensions.get("判断")));
        dimensionsvo.add(new Dimensions("抽象", dimensions.get("抽象")));
        dimensionsvo.add(new Dimensions("理性", dimensions.get("理性")));
        soulReportVo.setDimensions(dimensionsvo);//TODO
        PageInfo<SoulReport> pageInfo = this.soulReportApi.queryReportList(1, 50);
        List<SoulReport> records = pageInfo.getRecords();
        List<Long> userIds = new ArrayList<>();
        for (SoulReport record : records) {
            if (record.getUserId().longValue() == soulReport.getUserId().longValue()) {
                continue;
            }
            if (record.getConclusion().equals(soulReport.getConclusion())) {
                userIds.add(record.getUserId());
            }
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<Similar> similars = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            Similar similar = new Similar();
            similar.setId(userInfo.getUserId().intValue());
            similar.setAvatar(userInfo.getLogo());
            similars.add(similar);
        }
        soulReportVo.setSimilarYou(similars);


        return soulReportVo;
    }

    public String sub(List<Operation> operationList) {
        User user = UserThreadLocal.get();   //
        List<Questionnaire> questionnaireList = this.soulReportApi.getFindAll();  //得到三张问卷

        Integer total = 0;  //定义起始得分为0

        //遍历前段传过来的数据,去计算它的得分
        for (Operation operation : operationList) {
            String questionId = operation.getQuestionId();  //得到问卷编号
            String optionId = operation.getOptionId();      //得到试题编号
            //  问卷  -->题目-->选项  -->得分
            for (Questionnaire questionnaire : questionnaireList) {    //得到最外层的问卷内容  封面啥的
                List<Questions> questions = questionnaire.getQuestions();  //得到的是问题试题的内容  第一题
                //找到 对应的问卷
                if (questionId.equals(questionnaire.getTestId())) {    //是否是当前的问卷
                    for (Questions question : questions) {                 //遍历题目
                        List<Answers> answers = question.getAnswers(); //得到问卷试题选项
                        for (Answers answer : answers) {                //遍历选项
                            if (answer.getAnswerId().equals(optionId)) {   //当前选项
                                total += answer.getScore();
                                break;
                            }
                        }
                    }
                }

            }
            System.out.println(total);  //得到分数
        }

        SoulReport soulReport = new SoulReport();  //填入我们的表中
        soulReport.setTestId(operationList.get(0).getQuestionId());     //问卷的id
        soulReport.setUserId(user.getId().longValue());
        soulReport.setScore(total.doubleValue());

        //查看我的得分在哪个区间中,然后得到我的属性
        String attribute = null;
        String cover = null;
        if (total >= 0 && total < 21) {
            attribute = "猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。";

            cover = "http://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/logo/17.jpg";
        } else if (total >= 21 && total <= 40) {
            attribute = "白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。";
            cover = "http://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/logo/19.jpg";
        } else if (total >= 41 && total <= 55) {
            attribute = "狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。";
            cover = "http://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/logo/11.jpg";
        } else if (total > 56) {
            attribute = "狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。\n" +
                    "他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。";
            cover = "http://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/logo/16.jpg";
        }

        //进行封装到soulReport
        soulReport.setCover(cover);
        soulReport.setConclusion(attribute);

        Map<String, String> dimensions = new HashMap<>();
        dimensions.put("外向", "70%");
        dimensions.put("判断", "30%");
        dimensions.put("抽象", "90%");
        dimensions.put("理性", "30%");

        soulReport.setDimensions(dimensions);


        //最后塞到mongdb里面
        String s = this.soulReportApi.saveReport(soulReport);
        return s;
    }

    /**
     * @param
     * @return
     * @description 问卷列表
     * @author
     * @date
     */
    public List<SoulVo> queryQuestionnaire() {
        User user = UserThreadLocal.get();

        ArrayList<SoulVo> soulVoList = new ArrayList<>();

        // 从用户得分表中查看是否有问卷得分,若没有,返回初级问卷
        List<SoulReport> soulReports = soulReportApi.querySoulReportByUserId(user.getId());
        ArrayList<String> testIdList = new ArrayList<>();
        List<Questionnaire> questionnaires = soulReportApi.queryAll();

        for (Questionnaire questionnaire : questionnaires) {
            SoulVo soulVo = new SoulVo();
            soulVo.setId(questionnaire.getTestId());
            soulVo.setName(questionnaire.getName());
            soulVo.setCover(questionnaire.getCover());
            soulVo.setLevel(questionnaire.getLevel());
            soulVo.setStar(questionnaire.getStar());

            // 判断是否锁定
            switch (CollectionUtils.size(soulReports)) {
                case 0: {
                    if (questionnaire.getTestId().equals("1")) {
                        soulVo.setIsLock(0);
                    } else {
                        soulVo.setIsLock(1);
                    }
                    break;
                }
                case 1: {
                    if (questionnaire.getTestId().equals("1") || questionnaire.getTestId().equals("2")) {
                        soulVo.setIsLock(0);
                    } else {
                        soulVo.setIsLock(1);
                    }
                    break;
                }
                case 2:
                case 3: {
                    soulVo.setIsLock(0);
                    break;
                }
                default: {
                    return null;
                }
            }

            soulVo.setReportId(questionnaire.getReportId());

            List<QuestionsVo> questionsVosList = new ArrayList<>();


            List<Questions> questions = questionnaire.getQuestions();
            for (Questions question : questions) {
                // 添加题目
                QuestionsVo questionsVo = new QuestionsVo();
                questionsVo.setId(question.getTestId());
                questionsVo.setQuestion(question.getText());

                List<Answers> options = question.getAnswers();
                // 选项列表
                ArrayList<OptionsVo> optionList = new ArrayList<>();
                for (Answers option : options) {
                    // 添加选项
                    OptionsVo optionsVo = new OptionsVo();
                    optionsVo.setId(option.getAnswerId());
                    optionsVo.setOption(option.getText());
                    optionList.add(optionsVo);

                }
                questionsVo.setOptions(optionList);
                questionsVosList.add(questionsVo);
            }

            soulVo.setQuestions(questionsVosList);

            //查询最新的报告id - 徐
            SoulReport soulReport = this.soulReportApi.queryByUserId(user.getId(), questionnaire.getTestId());
            if (null != soulReport) {
                soulVo.setReportId(soulReport.getId().toHexString());
            }
            soulVoList.add(soulVo);
        }
        return soulVoList;
    }
}

